import axios, {
  AxiosError,
  AxiosResponse,
  Method,
  RawAxiosRequestHeaders,
} from "axios";
import router from "@/router";
import redux from "@/store";
import { Toast } from "antd-mobile";
//路由路径
const BASEURL = process.env.NODE_ENV === "development" ? "/api" : "/api";

export default function (
  url: string,
  data: object = {}, //给了默认值
  method: Method = "POST", //给了默认值
  headers: RawAxiosRequestHeaders = {} //给了默认值
) {
  return new Promise<IResponseData>((resolve, rejects) => {
    //登录凭证
    headers = Object.assign({}, headers, {
      "x-auth-token": redux.getState().user.token,
    });
    axios({
      url: BASEURL + url,
      method: method,
      headers: headers,
      params: method === "GET" ? data : null,
      data: method !== "GET" ? data : null,
      responseType: "json",
    })
      .then((res: AxiosResponse<any, any>) => {
        resolve(res.data);
      })
      .catch((err: AxiosError<any, any>) => {
        // console.log(err);
        if (err.response?.data.errCode === 1002) {
          //跳转登录页
          router.navigate("/login");
          Toast.show({
            icon: "loading",
            content: "加载中…",
            duration: 300,
          });
        }
        rejects(err);
      });
  });
}
